using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using LinkPointTransaction;
using System.Collections.Specialized;
using System.Configuration;
using SiteManager;
using System.Text;
using System.Data.SqlClient;
using System.IO;
/// <summary>
///    The page is designed and  developed to implement the functionality of Become
///    a feature dentist and it's complete implementation of your Pay Payment Gateway.
///    Author: Akash Saxena 
///    Date: 13 Oct 2007
/// </summary>
public partial class Dentist_DentistSubscription : System.Web.UI.Page
{
    /// <summary>
    /// Create object of manager and dentist Class Respectively
    /// </summary>
    Manager ObjManager = new Manager(true,"ConnectionString");
    //clsDentist ObjDentist = new clsDentist();
    Dentist ObjDentist = new Dentist();
    localFunction drchk = new localFunction();
    #region Variable Declaration
    /// <summary>
    /// Declare Variables
    /// </summary>
    protected string configfile;
    protected string keyfile;
    protected string host;
    protected int port;
    protected LinkPointTxn LPTxn;
    protected bool fLog = false;
    protected int logLvl = 0;
    protected string logFile = "";
    protected string baddrnum = "";
    protected string bzip = "";
    //protected string bCity = "";
    //protected string bState = "";
    protected string Name = "";
    protected string Email = "";
    protected string cardnumber = "";
    protected string expmonth = "";
    protected string expyear = "05";
    protected string total = "";
    //string strDate = "";
    protected string startdate = "";
    protected string periodicity = "";
    protected string installments = "";
    protected string pbthreshold = "";
    int iDentistId = 0;
    string SpecialityName = "";
    string errorMessage = String.Empty;
    string filename = String.Empty;
    #endregion
    protected static byte[] docimage;
    protected static HttpPostedFile Image;

    protected void Page_Load(object sender, EventArgs e)
    {
        Master.InnerRightBox = false;
        Master.InnerFeatureDocBox = true;
        WizardSubscription.FinishCompleteButtonText = "Complete Your Order";
        WizardSubscription.StartNextButtonText = "Continue";
        WizardSubscription.FinishPreviousButtonText = "Back";
        WizardSubscription.StepPreviousButtonText = "Back";
        WizardSubscription.StepNextButtonText = "Continue";

        //txtcardnumber.Attributes.Add("onkeypress", "return CheckCardNo(event)");
        //Check Dentist Login
        //drchk.checkDentistLogin(true);
        drchk.checkDentistLogin(true);

        ddlSubSpeciality.Enabled = false;
        //ddlSpeciality.Attributes.Add("onchange()", " return checkSubType();");
        ddlFeaturedDocType.Attributes.Add("onchange", "checkSelectedValue();");


        if (Session["userID"].ToString() != "" && Session["userID"] != null)
        {
            iDentistId = Convert.ToInt32(Session["userID"]);

        }
        if (!CheckDentistExist())
        {
            WizardSubscription.Visible = true;
            lblMessage.Text = "You are already registered.";
            mviewSubUsers.SetActiveView(viewOne);
            mviewSubUsers.Visible = true;
        }
        if (!Page.IsPostBack)
        {
            //Fill dropdowns
            LoadCommonControls();
            GetDentistDetails();
            YearDisplay();
            MonthDisplay();
            StateDisplay();//Added by Wahaj Khan April 29 2011
        }

        SpecialityDropDownSelectedValue();
        if (WizardSubscription.ActiveStepIndex == 2)
        {
      /*******************************************Commented by Wahaj Khan April 26 2011**********/
            if (CheckDentistExist())
            {
              //  Parse form data
                //ParseFormData();
                //// process order
                //ProcessOrder();


                ////Status Page
                //// Put user code to initialize the page here

                //HttpBrowserCapabilities bc = Request.Browser;
                //fIE5 = (bc.Browser == "IE" && bc.MajorVersion > 4);

                //order = (string)Session["outXml"];
                //resp = (string)Session["resp"];
                //ParseResponse(resp);

                //if (R_Approved == "APPROVED")
                //{
                //    SaveDataAfterApproval();
                //    // code for set IsActive false
                //    ObjManager.ExecuteScalarQuery("update coupons set IsActive='false',UsedAsOn=getdate() where couponcode='" + txtCouponCode.Text.ToString() + "' and Fordentistid='" + iDentistId + "'");
                //    //end code

                //}
                //setvalue();
                //SaveDataAfterApproval();
                //Session["couponcode"] = txtCouponCode.Text.ToString();
                //// code for set IsActive false
                //ObjManager.ExecuteScalarQuery("update coupons set IsActive='false',UsedAsOn=getdate() where couponcode='" + txtCouponCode.Text.ToString() + "' and ForDentistid='" + iDentistid + "'");
                ////end code

                ////}
               // Response.Redirect("Payment.aspx");
            /*******************************************Commented by Wahaj Khan April 26 2011**********/
            }
            else
            {
                //Response.Redirect(Session["strHttps"].ToString() + "Dentist/DentistContent.aspx");
            }

        }
        if (WizardSubscription.ActiveStepIndex == 0)
        {

            if (rbSubscription.Text == "2")//Monthly
            {
                if (ddlFeaturedDocType.Text == "1")//Standard Featured Dentist
                {
                    //txttotal.Text = "49";
                }
                if (ddlFeaturedDocType.Text == "2")//Enhanced Featured Dentist
                {
                    //txttotal.Text = "99";
                }
                if (ddlFeaturedDocType.Text == "3")//Premium Featured Dentist
                {
                    //txttotal.Text = "199";
                }
            }
            else if (rbSubscription.Text == "3")
            {
                if (ddlFeaturedDocType.Text == "1")
                {
                    //txttotal.Text = "499";
                }
                if (ddlFeaturedDocType.Text == "2")
                {
                    //txttotal.Text = "999";
                }
                if (ddlFeaturedDocType.Text == "3")
                {
                    //txttotal.Text = "1999";
                }

            }
            else
            {
                //txttotal.Text = "1";
            }

        }

        GetDentistDetails();


    }
    private void setvalue()
    {
        //SecurePay objSecurepay = new SecurePay();
        //objSecurepay.Name = txtName.Text;
        //objSecurepay.Street = txtbaddrnum.Text; ;
        //objSecurepay.City = txtCity.Text;
        //objSecurepay.State = ddlState.SelectedItem.Text; //txtState.Text;Commented by Wahaj April 29 2011
        //objSecurepay.Zip = txtbzip.Text;
        //objSecurepay.Email = txtEmail.Text;
        //objSecurepay.Amount = txttotal.Text;
        ////objSecurepay.CC_Name = ddlCardType.SelectedValue;
        //objSecurepay.CC_Number = txtcardnumber.Text;
        //objSecurepay.Month = ddlMonth.SelectedValue;
        //objSecurepay.Year = ddlYear.SelectedValue;
        //string period = rbSubscription.SelectedItem.ToString();
        //objSecurepay.TimeFrame = period;
        //objSecurepay.Rec_Amount = txttotal.Text;
        //objSecurepay.Start_Date = DateTime.Now.ToString();
        //Session["SetValue"] = objSecurepay;
    }
   
    private void ProcessOrder()
    {


        // create order            
        LPOrderPart order = LPOrderFactory.createOrderPart("order");
        // create a part we will use to build the order
        LPOrderPart op = LPOrderFactory.createOrderPart();

        // Build 'orderoptions'
        op.put("ordertype", "SALE");
        // add 'orderoptions to order
        order.addPart("orderoptions", op);

        // Build 'merchantinfo'
        op.clear();
        op.put("configfile", configfile);
        // add 'merchantinfo to order
        order.addPart("merchantinfo", op);

        // Build 'billing'
        // Required for AVS. If not provided, 
        // transactions will downgrade.
        op.clear();
        op.put("zip", bzip);
        //op.put("City", bCity);
        //op.put("State", bState);
        op.put("addrnum", baddrnum);
        // add 'billing to order
        order.addPart("billing", op);

        // Build 'creditcard'
        op.clear();
        op.put("cardnumber", cardnumber);
        op.put("cardexpmonth", expmonth);
        op.put("cardexpyear", expyear);
        // add 'creditcard to order
        order.addPart("creditcard", op);

        // Build 'payment'
        op.clear();
        op.put("chargetotal", total);
        // add 'payment to order
        order.addPart("payment", op);

        // build 'periodic' part
        op.clear();
        op.put("action", "SUBMIT");
        op.put("startdate", startdate);
        op.put("periodicity", periodicity);
        op.put("installments", installments);
        op.put("threshold", pbthreshold);
        // add 'periodic' to order
        order.addPart("periodic", op);

        // create transaction object	
        LPTxn = new LinkPointTxn();

        // get outgoing XML from the 'order' object
        string outXml = order.toXML();

        // Call LPTxn
        string resp = LPTxn.send(keyfile, host, port, outXml);

        //Store transaction data on Session and redirect
        Session["outXml"] = outXml;
        Session["resp"] = resp;
    }

    private void GetDentistDetails()
    {
        SqlDataReader objDataReader = null;

        objDataReader = ObjManager.ExecuteQuery("select (fname +' ' + Mname+ ' ' +Lname)as DentistName,Email,(Address1 +' '+Address2)as Address,City,State,ZipCode  from tbl_Dentists where id=" + iDentistId);

        if (objDataReader.HasRows)
        {
            objDataReader.Read();
            /*******************************************Commented by Wahaj Khan April 28 2011**********/
            //txtName.Text = objDataReader["DentistName"].ToString();
            //txtbaddrnum.Text = objDataReader["Address"].ToString();
            //txtCity.Text = objDataReader["City"].ToString();
            //ddlState.SelectedItem.Text
            //txtState.Text = objDataReader["State"].ToString();
            //txtbzip.Text = objDataReader["ZipCode"].ToString();
            /*******************************************End Commented by Wahaj Khan April 28 2011**********/

           // txtEmail.Text = objDataReader["Email"].ToString();

        }
        objDataReader.Close();
        objDataReader.Dispose();
    }

    /*******************************************Function Added by Wahaj Khan April 29 2011**********/

    private void StateDisplay()
    {
        //Manager mgr = new Manager(true,"ConnectionString");
        //mgr.BindList("select stateid,name from tbl_states order by name", "Name", "StateId", ddlState, "State :");
    }

    /*******************************************End Function by Wahaj Khan April 29 2011**********/


    private void YearDisplay()
    {
       // ddlYear.Items.Insert(0, "Year");
        for (int i = 2007; i < 2021; i++)
        {
           // ddlYear.Items.Add(i.ToString());
        }
    }
    private void MonthDisplay()
    {
    //    DataTable tbMonth = new DataTable();
    //    tbMonth.Columns.Add(new DataColumn("MonthNo"));
    //    tbMonth.Columns.Add(new DataColumn("MonthName"));
    //    tbMonth.Rows.Add(new object[] { "01", "Jan" });
    //    tbMonth.Rows.Add(new object[] { "02", "Feb" });
    //    tbMonth.Rows.Add(new object[] { "03", "Mar" });
    //    tbMonth.Rows.Add(new object[] { "04", "Apr" });
    //    tbMonth.Rows.Add(new object[] { "05", "May" });
    //    tbMonth.Rows.Add(new object[] { "06", "Jun" });
    //    tbMonth.Rows.Add(new object[] { "07", "July" });
    //    tbMonth.Rows.Add(new object[] { "08", "Aug" });
    //    tbMonth.Rows.Add(new object[] { "09", "Sep" });
    //    tbMonth.Rows.Add(new object[] { "10", "Oct" });
    //    tbMonth.Rows.Add(new object[] { "11", "Nov" });
    //    tbMonth.Rows.Add(new object[] { "12", "Dec" });
        //ddlMonth.DataSource = tbMonth;
        //ddlMonth.DataValueField = "MonthNo";
        //ddlMonth.DataTextField = "MonthName";
        //ddlMonth.DataBind();
        //ddlMonth.Items.Insert(0, "Month");

    }
    protected void ParseFormData()
    {
        //bzip = txtbzip.Text;
        ////bState = ddlState.SelectedItem.Text; //txtState.Text.Trim().ToString();Commented by Wahaj April 29 2011
        ////bCity = txtCity.Text.Trim().ToString();
        //baddrnum = txtbaddrnum.Text;
        //cardnumber = txtcardnumber.Text;
        //expmonth = ddlMonth.SelectedValue.ToString();
        //string r = ddlYear.SelectedValue.ToString();
        //r = r.Substring(2);
        //expyear = r;
        //total = txttotal.Text;
        //Name = txtName.Text;
        //Email = txtEmail.Text;
        //if ((total == null) || total.Length < 1) { total = "0.0"; }
        //pbthreshold = "3";
        ////strDate = System.DateTime.Now.ToShortDateString();
        ////startdate = DateTime.Parse(strDate).ToString("yyyyMMdd");
        //startdate = "immediate";
        //periodicity = rbSubscription.SelectedItem.ToString();
        //installments = "99";
        //GetConfigParams();
    }
    private void SpecialityDropDownSelectedValue()
    {
        SqlDataReader objDataReader = null;
        objDataReader = ObjManager.ExecuteQuery("select tbl_DentistSpecialty.Specialty,tbl_DentistSpecialty.id,tbl_Dentists.fName from tbl_Dentists inner join tbl_DentistSpecialty  on tbl_DentistSpecialty.id =tbl_Dentists.SpecialityID  and tbl_Dentists.id=" + iDentistId);

        if (objDataReader.HasRows)
        {
            objDataReader.Read();
            SpecialityName = objDataReader["id"].ToString();
            if (SpecialityName.Length.Equals(0))
            {
                objDataReader.Close();
                return;
            }
            else
            {
                ddlSpeciality.SelectedValue = SpecialityName;
                objDataReader.Close();
            }
        }
        else
        {
            objDataReader.Close();
        }
        objDataReader.Dispose();
    }
    private bool CheckDentistExist()
    {
        int id = Convert.ToInt32(Session["userID"]);

        object objcount = ObjManager.ExecuteScalarQuery("select count(DentistId) from DentistSubscription where DentistId=" + Convert.ToInt32(Session["userID"]));
        if (Convert.ToString(objcount) == "0")
        {
            return true;
        }
        else
        {
            return false;

        }

    }
    
    private void GetConfigParams()
    {
        // get some stuff from app config
        //NameValueCollection config1 = (NameValueCollection)ConfigurationSettings.GetConfig("LPAPP_Config/client"); commented at 131008 to fix warning
        NameValueCollection config1 = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("LPAPP_Config/client");


        configfile = config1["Configfile"];
        keyfile = config1["Keyfile"];
        host = config1["Host"];
        port = Int32.Parse(config1["Port"]);

        //NameValueCollection config = (NameValueCollection)ConfigurationSettings.GetConfig("LPAPP_Config/opts"); commented at 131008 to fix warning

        NameValueCollection config = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("LPAPP_Config/opts"); 

        try
        {
            fLog = bool.Parse(config["fLog"]);
        }
        catch (Exception) { }

        try
        {
            logLvl = Int32.Parse(config["logLvl"]);
        }
        catch (Exception) { }

        try
        {
            logFile = config["logFile"];
        }
        catch (Exception) { }

    }
    private void LoadCommonControls()
    {
        ObjManager.BindList("select id,Specialty from tbl_DentistSpecialty order by Specialty", "Specialty", "id", ddlSpeciality, "");
        ObjManager.BindList("select id,specialty from tbl_DentistSubSpecialty order by specialty", "specialty", "Id", ddlSubSpeciality, " Sub specialty");
        ObjManager.BindList("select FeatureDocTypeId,FeatureDocType from  tbl_FeatureDocType", "FeatureDocType", "FeatureDocTypeId", ddlFeaturedDocType, "");

        ddlFeaturedDocType.Items.Insert(0, new ListItem("Select", "0"));
        //rbSubscription.Items.Add(new ListItem("Daily", "1"));
        //rbSubscription.Items[0].Selected = true;
        rbSubscription.Items.Add(new ListItem("Monthly", "2"));
        rbSubscription.Items.Add(new ListItem("Annual", "3"));
        rbSubscription.Items[0].Selected = true;
        if (!CheckDentistExist())
        {
            Manager mgr = new Manager(true, "ConnectionString");
            DataSet ds = CustomRepository.CustumDataSetFunction("select * from tbl_dentists where  isdelete=0 and id=" + Convert.ToInt32(Session["userID"]), "tblDentists");
            string FeatureDocTypeId = Convert.ToString(ds.Tables[0].Rows[0]["FeatureDocTypeId"]);
            ddlFeaturedDocType.SelectedValue = FeatureDocTypeId;

        }

    }
  
    protected void ParseResponse(string rsp)
    {
        R_Time = ParseTag("r_time", rsp);
        R_Ref = ParseTag("r_ref", rsp);
        R_Approved = ParseTag("r_approved", rsp);
        R_Code = ParseTag("r_code", rsp);
        R_Authresr = ParseTag("r_authresronse", rsp);
        R_Error = ParseTag("r_error", rsp);
        R_OrderNum = ParseTag("r_ordernum", rsp);
        R_Message = ParseTag("r_message", rsp);
        R_Score = ParseTag("r_score", rsp);
        R_TDate = ParseTag("r_tdate", rsp);
        R_AVS = ParseTag("r_avs", rsp);
        R_Tax = ParseTag("r_tax", rsp);
        R_Shipping = ParseTag("r_shipping", rsp);
        R_FraudCode = ParseTag("r_fraudCode", rsp);
        R_ESD = ParseTag("esd", rsp);
    }

    protected string ParseTag(string tag, string rsp)
    {
        StringBuilder sb = new StringBuilder(256);
        sb.AppendFormat("<{0}>", tag);
        int len = sb.Length;
        int idxSt = -1, idxEnd = -1;
        if (-1 == (idxSt = rsp.IndexOf(sb.ToString())))
        { return ""; }
        idxSt += len;
        sb.Remove(0, len);
        sb.AppendFormat("</{0}>", tag);
        if (-1 == (idxEnd = rsp.IndexOf(sb.ToString(), idxSt)))
        { return ""; }
        return rsp.Substring(idxSt, idxEnd - idxSt);
    }

    protected string order;
    protected string resp;
    protected bool fIE5;
    protected string R_Time;
    protected string R_Ref;
    protected string R_Approved;
    protected string R_Code;
    protected string R_Authresr;
    protected string R_Error;
    protected string R_OrderNum;
    protected string R_Message;
    protected string R_Score;
    protected string R_TDate;
    protected string R_AVS;
    protected string R_FraudCode;
    protected string R_ESD;
    protected string R_Tax;
    protected string R_Shipping;

    private void SaveDataAfterApproval()
    {
        //Write Code to add the processed value in database
        ObjDentist.DentistId = iDentistId;
        ObjDentist.TransactionId = "111111";
        ObjDentist.TransactionDate =Convert.ToString(DateTime.Now);// R_Time;//need to confirm  which date should be add ?? R_Time or startdate.
       // ObjDentist.TransactionAmount = txttotal.Text.ToString();
        ObjDentist.SubscriptionId = "222222";
        ObjDentist.SubscriptionType = rbSubscription.SelectedItem.ToString();
        ObjDentist.FeatureDentistTypeId= Convert.ToInt32(ddlFeaturedDocType.Text);
        ObjDentist.SpecialityId = Convert.ToInt32(ddlSpeciality.Text);

        ObjDentist.SubSpecialityId = Convert.ToInt32(ddlSubSpeciality.Text); 

        ObjDentist.photo = ViewState["sfilename"].ToString();
        ObjDentist.prof_desc = txtdoctorStatement.Text.Trim().ToString();
        ObjDentist.IsCheck = false;
        ObjDentist.website = txtWebSite.Text.Trim().ToString();
        ObjManager.ExecuteScalarQuery("update tbl_Dentists set FeatureDocTypeId ='" + ObjDentist.FeatureDentistTypeId + "' where id ='" + ObjDentist.DentistId + "'");
        if (chechDentistInSub())
        {
            ObjDentist.InsertDentistSubscription();
        }
        else
        {
            ObjManager.ExecuteScalarQuery("Update DentistSubscription set FeatureDocTypeId='" + ObjDentist.FeatureDentistTypeId + "'  where DentistId='" + ObjDentist.DentistId + "'");
       }
       
    }

    private bool chechDentistInSub()
    {
        int id = Convert.ToInt32(Session["userID"]);

        object objcount = ObjManager.ExecuteScalarQuery("select count(DentistId) from DentistSubscription where DentistId=" + Convert.ToInt32(Session["userID"]));
        if (Convert.ToString(objcount) == "0")
        {
            return true;
        }
        else
        {
            return false;

        }
    }
    
    /// <summary>
    /// This Function is created for Checking Coupon Code  
    /// 1)is active or not ??
    /// 2)and For which Doctor/Dentist is Created for 
    /// 3) and It also checks that This Coupon weather already used  or not ??
    /// </summary>
    private bool CheckCouponCodeExist()
    {

        ObjDentist.UserType= 2;
        ObjDentist.LoginID = Convert.ToInt32(Session["userID"]);
        if (txtCouponCode.Text.ToString().Length.Equals(0))
            return true;
        ObjDentist.CouponCode= txtCouponCode.Text.Trim().ToString();

        return ObjDentist.CheckCouponCode();
    }


    //
    protected void WizardSubscription_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        lblWS1Message.Text = string.Empty;
        lblErrorMessage.Text = string.Empty;
        if (WizardSubscription.ActiveStepIndex == 0)
        {
            if (CheckCouponCodeExist())
            {
                //lblWS1Message.Text = string.Empty;
            }
            else
            {
                // Response.Redirect("DentistSubscription.aspx?msg=Invalid Coupon Code");
                lblWS1Message.Text = "Invalid Coupon Code";
                WizardSubscription.MoveTo(WizardStep1);
                e.Cancel = true;
            }
        }
        if (WizardSubscription.ActiveStepIndex == 1)
        {
            //string errorMessage = String.Empty;
            //string filename = String.Empty;
            // upload the Dentist's image
            ViewState["sfilename"] = "";
            if (fUpload_photo.HasFile)
            {
                string ImgPath1 = "../images/Dnt_images/";
                string filename1 = Path.GetFileName(fUpload_photo.PostedFile.FileName);
                string baseFile = Path.GetFileNameWithoutExtension(fUpload_photo.PostedFile.FileName);
                string extension = Path.GetExtension(fUpload_photo.PostedFile.FileName);
                int fileMatchCount = 1;
                // Check if a file with the given name exists in the Images1 subfolder of the root folder of your site
                while (File.Exists(Server.MapPath(Path.Combine(ImgPath1, filename1))))
                {
                    //filename1 = string.Format("{0}({1:D3}){2}", baseFile, fileMatchCount, extension);
                    filename1 = string.Format("{0}({1:D2}){2}", baseFile, fileMatchCount, extension);
                    fileMatchCount++;
                }
                fUpload_photo.SaveAs(Server.MapPath(Path.Combine(ImgPath1, filename1)));
                //Session["photo"] = filename1;
                if (filename1.Length > 0)
                {
                    ViewState["sfilename"] = filename1;
                }
            }
           
        }
        /**************************************Added By Wahaj Khan April 28 2011*****************/
        if (WizardSubscription.ActiveStepIndex == 2)
        {
            if (CheckDentistExist())
            {
                setvalue();
                SaveDataAfterApproval();
                Session["couponcode"] = txtCouponCode.Text.ToString();
                Response.Redirect("Payment.aspx");
            }
        }
        /**************************************Added By Wahaj Khan April 28 2011*****************/
    }

    protected void WizardSubscription_PreviousButtonClick(object sender, WizardNavigationEventArgs e)
    {
        //Response.Write("Hello");
        //Response.End();
    }
    /**********************************Added by Wahaj Khan April 28 2011*********************************/

    protected void WizardSubscription_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        if (WizardSubscription.ActiveStepIndex == 2)
        {
            //if (CheckDentistExist())
            //{
                setvalue();
                SaveDataAfterApproval();
                Session["couponcode"] = txtCouponCode.Text.ToString();
               // Response.Redirect("Payment.aspx");
            //}
        }
    }
  
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string filename1 = "";
        if (fupl_photoSUB.HasFile)
        {
            string ImgPath1 = "../images/Dnt_images/";
             filename1 = Path.GetFileName(fupl_photoSUB.PostedFile.FileName);
            string baseFile = Path.GetFileNameWithoutExtension(fupl_photoSUB.PostedFile.FileName);
            string extension = Path.GetExtension(fupl_photoSUB.PostedFile.FileName);
            int fileMatchCount = 1;
            // Check if a file with the given name exists in the Images1 subfolder of the root folder of your site
            while (File.Exists(Server.MapPath(Path.Combine(ImgPath1, filename1))))
            {
                //filename1 = string.Format("{0}({1:D3}){2}", baseFile, fileMatchCount, extension);
                filename1 = string.Format("{0}({1:D2}){2}", baseFile, fileMatchCount, extension);
                fileMatchCount++;
            }
            fupl_photoSUB.SaveAs(Server.MapPath(Path.Combine(ImgPath1, filename1)));
            //Session["photo"] = filename1;
            if (filename1.Length > 0)
            {
                ViewState["sfilename"] = filename1;
            }
        }

        ObjDentist.DentistId = iDentistId;
        ObjDentist.photo = filename1; // ViewState["sfilename"].ToString();
        ObjDentist.prof_desc = txtDocStatementSUB.Text.Trim().ToString();
        ObjDentist.website = txtWebSiteSUB.Text.Trim().ToString();
        ObjDentist.FeatureDentistTypeId =Convert.ToInt32( ddlFeaturedDocType.SelectedValue);
        //ObjDentist.image = docimage;
        //localFunction th = new localFunction();

        //ObjDentist.th_image = th.getThumbnaleImage(docimage, 80, 100);
        ObjManager.ExecuteScalarQuery("update tbl_Dentists set FeatureDocTypeId ='" + ObjDentist.FeatureDentistTypeId + "' where id ='" + ObjDentist.DentistId + "'");

        ObjDentist.UpdateDentistSubscription();
       
        //     Response.Write(iDentistId + " " + txtDocStatementSUB.Text.Trim().ToString() + " " + txtWebSiteSUB.Text.Trim().ToString());
        //     Response.Write("UPDATED");
    }
      
}
